package com.huang.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.eduservice.entity.EduSubject;
import com.huang.eduservice.entity.excel.SubjectData;
import com.huang.eduservice.service.EduSubjectService;
import com.huang.servicebase.execptionhandler.huangException;



public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //因为SubjectExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    public EduSubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //一行一行读取excel中数据
            if(subjectData==null){
                throw new huangException(20001,"读取数据为空");
            }
                EduSubject oneSub = this.existOneSub(subjectService, subjectData.getOneSubjectName());
                if(oneSub==null){
                    oneSub=new EduSubject();
                    oneSub.setParentId("0");
                    oneSub.setTitle(subjectData.getOneSubjectName());
                    subjectService.save(oneSub);
                }
                String pid=oneSub.getId();
                EduSubject twoSub = this.existTwoSub(subjectService, subjectData.getTwoSubjectName(), pid);
                if(twoSub==null){
                   twoSub= new EduSubject();
                   twoSub.setTitle(subjectData.getTwoSubjectName());
                   twoSub.setParentId(pid);
                   subjectService.save(twoSub);
                }

    }
    private EduSubject existOneSub(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSub = subjectService.getOne(wrapper);
        return oneSub;

    }
    private EduSubject existTwoSub(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSub = subjectService.getOne(wrapper);
        return twoSub;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
